<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
    <style>
        table {
            border: 1px solid #e0e0e0;
            border-collapse: collapse;
        }

        td {
            border: 1px solid #e0e0e0;
        }
    </style>
</head>

<body>
    <header class="aui-bar aui-bar-nav main-header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            生产入库
        </div>
    </header>
    <div class="aui-bar aui-bar-nav sub-header"></div>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;padding-bottom: 50px;">
        <div class="white_background">
            <ul class="aui-list aui-form-list">

                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">目标库位</div>
                        <!-- <div class="aui-list-item-label1" style="margin-top:5px;font-size: 14px;">
                        <img src="../image/scanner.png" />
                    </div> -->
                        <input type="text" class="aui-input" placeholder="请扫描目标库位" style="width: 80%;font-size: 16px;"
                            id="relWorkCellCode" onclick="getIdSelector();" />
                        <i class="aui-input-addon aui-iconfont aui-icon-scan "
                            style="padding-right:10px;font-size: 1.6rem" onclick="doScan();"></i>
                    </div>
                </li>
                <li class="aui-list-item">
                    <div class="aui-list-item-inner">
                        <div class="aui-list-item-label">容器码</div>
                        <!-- <div class="aui-list-item-label1" style="margin-top:5px;font-size: 14px;">
                        <img src="../image/scanner.png" />
                    </div> -->
                        <input type="text" class="aui-input" placeholder="请扫描容器码" style="width: 80%;font-size: 16px;"
                            id="rsBarcode" onclick="getIdSelector();" />
                        <i class="aui-input-addon aui-iconfont aui-icon-scan "
                            style="padding-right:10px;font-size: 1.6rem" onclick="doScan();"></i>
                    </div>
                </li>
                <div class="aui-btn aui-btn-info aui-btn-block"><input type="text" class="aui-input"
                        style="width: 90%;font-size: 16px;color:#fff;" readonly id="message" /></div>
                <div style="background-color:white;width: 100%;margin-top:2%;margin-bottom:5px;">
                    <table class="table" style='width:100%;' id="table">
                        <thead>
                            <tr style="text-align: center;color: #757575;font-size: 8px;font-weight: bold;">
                                <td algin='center'>物料编码</td>
                                <td algin='center'>规格</td>
                                <td algin='center'>汇总数量</td>
                            </tr>
                        </thead>
                        <tbody id="tbodyHtml">
                        </tbody>
                    </table>
                </div>
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label" style="margin-left:30%;width:100%">扫描箱数：</div>
                    <div class="aui-list-item-input" style="margin-left:5%">
                        <input type="text" id="num" value="" disabled="true" style='color:red' />
                    </div>
                </div>
            </ul>
        </div>
        <ul class="ui-selectee" id="tbodyHtmlS">

        </ul>

        <p></p>
        <p></p>
        <div style="height:60px;"></div>
        <footer class="aui-bar aui-bar-tab" id="footer">
            <div class="aui-btn aui-btn-info aui-btn-block" style="margin:0 5%;width: 90%;" id="submitButton"
                onclick="save()">一键入库</div>

        </footer>

    </div>


</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script type="text/javascript">
    //光标所在id
    //光标所在id
    var idSelector = "";
    var workCellGid = ""; //调出库位GID
    var workCellCode = ""; //调出库位编码
    var workCellName = ""; //调出库位名称
    var relWorkCellGid = ""; //调入库位GID
    var relWorkCellCode = ""; //调入库位编码
    var relWorkCellName = ""; //调入库位名称


    var scanRule = ""; //条码解析规则

    var workcell; //菜单路由参数 源库位编码
    var relworkcell; //菜单路由参数 调入库位编码
    var subBussinessType = "";//库间转移子业务类型

    var arrSave = [];
    var rsCodeList = "";

    var code; //菜单路由参数
    var codesub; //菜单路由参数

    var num = 0;

    //初始化查询仓库下拉框
    apiready = function () {

        $("#relWorkCellCode").focus();
        idSelector = "relWorkCellCode";

        var query = api.pageParam.query;
        code = query.code
        codesub = query.codesub

        var title = query.title;
        if (title != undefined && title != null && title != "") {
            document.getElementById("title").innerHTML = title;
        }
        $("#num").val(0);
        //查询条码解析规则
        initScanRule();
    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //查询扫描规则
    function initScanRule() {
        var serverUrl = localStorage.getItem('serverUrl');
        var un = localStorage.getItem("un");
        var url = serverUrl + "/app/getTmScanRule";
        var data = {
            values: {
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    scanRule = myobj.scanRule
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    //扫描
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {
            //1：调出库位
            if (idSelector == 'workCellCode') {

                $("#workCellCode").val(ret);
                //查询调出库位
                getWorkCell(ret, idSelector, "1");

                //24：调入库位
            } else if (idSelector == 'relWorkCellCode') {

                $("#relWorkCellCode").val(ret);
                //查询调入库位
                getWorkCell(ret, idSelector, "2");

                //5：扫描条码
            } else if (idSelector == 'rsBarcode') {
                $("#rsBarcode").val(ret);
                doSerchRsCode(ret)
            }
        });
    }

    //7:库位扫描校验
    function getWorkCell(code, inputId, flag) {
        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getWorkCell";
        var data = {
            values: {
                flag: "out_kj", //库内库间标识（out_kn库内  out_kj库间,in_rk入库出库）
                workCenterGid: "", //仓库GID
                workCellCode: code, //库位编码
                relWorkCellGid: "", //调入库位
                tm: "",
                workCellFlag: "", //原库位调入库位flag
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {
                    var list = eval(myobj.list);

                    //源库位
                    if (flag == "1") {

                        workCellGid = list[0].workCellGid;
                        workCellCode = list[0].workCellCode + ":" + list[0].workCellName;
                        workCellName = list[0].workCellName;
                        document.getElementById(inputId).value = workCellCode;
                        $("#rsBarcode").attr('disabled', false);
                        $("#rsBarcode").focus();
                        idSelector = "rsBarcode";

                        //调入库位
                    } else if (flag == "2") {

                        relWorkCellGid = list[0].workCellGid;
                        relWorkCellCode = list[0].workCellCode + ":" + list[0].workCellName;
                        relWorkCellName = list[0].workCellName;
                        document.getElementById(inputId).value = relWorkCellCode;
                        $("#rsBarcode").focus();
                        idSelector = "rsBarcode";
                    }
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                    $("#" + inputId).focus();
                    $("#" + inputId).select();
                }
            }
        });
    }

    //8：选择库位
    function goSelectWorkCell(workCellFlag) {
        var tm = $("#tm").val();
        api.openWin({
            name: 'uwmSelectWorkCell',
            url: 'uwmSelectWorkCell.html',
            pageParam: {
                flag: "out_kj",
                name: "taskFreeDistribution",
                tm: tm,
                workCenterGid: "",
                relWorkCellGid: relWorkCellGid,
                workCellFlag: workCellFlag
            }
        });
    }


    //7；PDA自带扫描回车事件-库位
    $("#rsBarcode").on('keypress', function (e) { //#keyword为input文本框
        console.log(5555555555)
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            $("#rsBarcode").val(sm);
            doSerchRsCode(sm)
        }
    });

    //库位选择后回调函数
    function setWorkCell(id, code, name, workCellFlag) {

        //源库位
        if (workCellFlag == "1") {

            workCellGid = id;
            workCellCode = code;
            workCellName = name;
            document.getElementById('workCellCode').value = code + ":" + name;

            //调入库位
        } else if (workCellFlag == "2") {

            relWorkCellGid = id;
            relWorkCellCode = code;
            relWorkCellName = name;
            document.getElementById('relWorkCellCode').value = code + ":" + name;
            $("#rsBarcode").focus();
            var e = "rsBarcode";
            idSelector = e;
        }
    }

    //9；PDA自带扫描回车事件-源库位
    $("#workCellCode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {

            $("#workCellCode").val(sm);
            getWorkCell(sm, "workCellCode", "1");
        }
    });

    //10；PDA自带扫描回车事件-调入库位
    $("#relWorkCellCode").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {

            $("#relWorkCellCode").val(sm);
            getWorkCell(sm, "relWorkCellCode", "2");
        }
    });


    // function beforeSave() {
    //     api.confirm({
    //         title: '温馨提示',
    //         msg: '您确定要创建配送单吗？',
    //         buttons: ['确定', '取消']
    //     }, function (ret, err) {
    //         if (ret.buttonIndex == 1) {
    //             save()
    //         }
    //     });
    // }

    function doSerchRsCode(rsBarcode) {
        console.log(111111)
        console.log(rsBarcode)
        //判断容器条码是否重复
        for (var i = 0; i < arrSave.length; i++) {
            if (rsBarcode == arrSave[i].rsBarcode) {
                $("#rsBarcode").val("");
                api.toast({
                    msg: '容器码已存在！',
                    duration: 3000
                });
                return;
            }
        }
        console.log(4444444444)
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/doSearchTrayXn";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                un: un,
                sm: rsBarcode,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                console.log(myobj.code)
                //成功
                if (myobj.code == '0') {
                    api.hideProgress();
                    message = "提示信息：" + rsBarcode + "   扫描成功"
                    $("#message").val(message);
                    message = "";
                    rsCodeList = rsCodeList + "," + rsBarcode;
                    doSerchRsCodeList(rsCodeList);
                } else if (myobj.code == '1') {
                    $("#rsBarcode").val("");
                    api.hideProgress();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                $("#rsBarcode").val("");
                $("#rsBarcode").select();
                idSelector = "rsBarcode";
                api.hideProgress();
                alert("连接超时，请耐心等待");
            }
        });
    }


    function doSerchRsCodeList(rsCodeList) {
        console.log(2222222222)
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/doSerchRsCodeList";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                un: un,
                rsCodeList: rsCodeList,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                console.log(333333333)
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {
                    var list = eval(myobj.list);
                    var listS = eval(myobj.listS);
                    console.log(listS)
                    var html = "";
                    for (var i = 0; i < list.length; i++) {
                        html += "<tr style='text-align: center;color: black;font-size: 10px;'>";
                        html += "<td name='mrlCode'>" + list[i].mrlCode + "</td>";
                        html += "<td name='drawing'>" + list[i].drawing + "</td>";
                        html += "<td name='qty'>" + list[i].qty + "</td>";
                        html += "</tr>";
                    }
                    $api.html($api.byId("tbodyHtml"), html);

                    $("#rsBarcode").val("");
                    arrSave = [];
                    for (var i = 0; i < listS.length; i++) {
                        var model = {
                            rsCode: listS[i].ctCode, //
                            rsBarcode: listS[i].ctBarCode, //
                            rsName: listS[i].ctName, //
                            returnMsg: listS[i].returnMsg,
                        }
                        arrSave.push(model);

                    }
                    $("#num").val(listS.length);
                    num = listS.length
                    setTable(arrSave);
                } else if (myobj.code == '1') {
                    $("#rsBarcode").val("");
                    api.hideProgress();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    // const submitButton = document.getElementById('submitButton');
    // submitButton.addEventListener('click', async () => {

    //     try {
    //         // 模拟后台处理请求
    //         save();
    //         console.log('表单已提交，处理成功');
    //     } catch (error) {
    //         console.log('表单提交失败');
    //     } finally {
    //         submitButton.style.pointerEvents = "auto"; // 启用提交按钮
    //         console.log('执行finally');
    //     }
    // });

    //保存按钮
    function save() {
        if (!clickThrottle()) {
            return;
        }

        // 容器码
        var rsBarcode = $("#rsBarcode").val();

        const submitButton = document.getElementById('submitButton');
        // submitButton.disabled = true; // 禁用提交按钮
        // $("#submitButton").attr('disabled', true);
        submitButton.style.pointerEvents = "none"; // 禁用提交按钮

        //调入库位非空校验
        if (relWorkCellGid == "" || relWorkCellGid == null || relWorkCellGid == undefined) {
            api.toast({
                msg: '请选择/扫描 目标库位',
                duration: 3000
            });
            submitButton.style.pointerEvents = "auto"; // 启用提交按钮
            return;
        }
        // //容器码非空校验
        // if (rsBarcode == "" || rsBarcode == null || rsBarcode == undefined) {
        //     api.toast({
        //         msg: '请扫描容器码',
        //         duration: 3000
        //     });
        //     submitButton.style.pointerEvents = "auto"; // 启用提交按钮
        //     return;
        // }

        api.showProgress({
            title: '保存中...',
        });


        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/finishStockInSave";
        var data = {
            values: {
                relWorkCellGid: relWorkCellGid, // 调入库位
                list: JSON.stringify(arrSave),
                businessType: code, //业务类型
                subBusinessType: codesub, // 子业务类型
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {
                    submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                    api.hideProgress();
                    api.toast({
                        msg: "保存成功",
                        duration: 3000
                    }); //清空表单

                    $("#rsBarcode").attr('disabled', false);
                    $("#message").val(myobj.message);
                    $("#rsBarcode").focus();
                    idSelector = "rsBarcode";

                    //清空表格数据
                    $api.html($api.byId("tbodyHtml"), "");
                    $("#num").val(0);
                    arrSave = [];
                    num = 0;
                    setTable(arrSave);
                    rsCodeList = "";
                } else if (myobj.code == '1') {
                    submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                    api.hideProgress();
                    $("#message").val(myobj.message);
                    rsCodeList = myobj.rsCodeList
                    var list = eval(myobj.list);
                    var listS = eval(myobj.listS);
                    var html = "";
                    for (var i = 0; i < list.length; i++) {
                        html += "<tr style='text-align: center;color: black;font-size: 10px;'>";
                        html += "<td name='mrlCode'>" + list[i].mrlCode + "</td>";
                        html += "<td name='drawing'>" + list[i].drawing + "</td>";
                        html += "<td name='qty'>" + list[i].qty + "</td>";
                        html += "</tr>";
                    }
                    $api.html($api.byId("tbodyHtml"), html);
                    $("#rsBarcode").val("");
                    arrSave = [];
                    for (var i = 0; i < listS.length; i++) {
                        var model = {
                            rsCode: listS[i].ctCode, //
                            rsBarcode: listS[i].ctBarCode, //
                            rsName: listS[i].ctName, //
                            returnMsg: listS[i].returnMsg,
                        }
                        arrSave.push(model);

                    }
                    $("#num").val(listS.length);
                    num = listS.length
                    setTable(arrSave);
                }
            } else {
                submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                $("#rsBarcode").attr('disabled', false);
                $("#rsBarcode").val("");
                $("#rsBarcode").select();
                idSelector = "rsBarcode";
                api.hideProgress();
                $("#message").val("");
                alert(JSON.stringify(err));
            }
        });

        // submitButton.style.pointerEvents = "auto";

        console.log('执行完save');

    }



    function setTable(list) {
        var html = "";
        for (var i = 0; i < list.length; i++) {
            html += "<li class='sortable ui-selectee ui-sortable'>";
            html += "<div class='white_background'>"
            html += "<ul class='aui-list aui-form-list ui-selectee'>";

            html += "<li class='aui-list-item  ui-selectee'>";
            html += "<div class='aui-list-item-inner ui-selectee'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>容器条码：</div>";
            html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].rsBarcode + "</div>";
            html += "</div>";
            html += "</li>";

            html += "<li class='aui-list-item  ui-selectee'>";
            html += "<div class='aui-list-item-inner ui-selectee'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>容器编码：</div>";
            html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].rsCode + "</div>";
            html += "</div>";
            html += "</li>";

            html += "<li class='aui-list-item  ui-selectee'>";
            html += "<div class='aui-list-item-inner ui-selectee'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>容器名称：</div>";
            html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].rsName + "</div>";
            html += "</div>";
            html += "</li>";

            console.log(list[i].returnMsg)
            if (list[i].returnMsg != "" && list[i].returnMsg != null && list[i].returnMsg != undefined) {
                html += "<li class='aui-list-item  ui-selectee'>";
                html += "<div class='aui-list-item-inner ui-selectee'>";
                html += "<div class='aui-list-item-label ui-selectee list-tr-title'>失败原因：</div>";
                html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].returnMsg + "</div>";
                html += "</div>";
                html += "</li>";
            }

            html += "<li class='aui-list-item  ui-selectee' style='background-color:white;'>";
            html += "<div class='aui-btn aui-btn-info aui-btn-block ui-selectee' style='background:red !important;color:white;margin:0 25%;width:50%;' onclick='remove(\"" + list[i].rsBarcode + "\");'>移除</div>";
            html += "</li>";

            html += "</ul>";
            html += "</div>";
            html += "</li>";
        }
        $api.html($api.byId("tbodyHtmlS"), html);
    };
    function remove(rsBarcode) {
        for (var i = 0; i < arrSave.length; i++) {
            if (arrSave[i].rsBarcode == rsBarcode) {
                num = num - 1;
                arrSave.splice(i, 1)
                $("#num").val(num);
                setTable(arrSave);
            }

        }

        // 将逗号拼接的字符串转换为数组
        var arr = rsCodeList.split(',');

        // 使用filter方法过滤掉指定的值
        // arr = arr.filter(item => item !== rsBarcode);

        arr = arr.filter(function (item) {
            return item !== rsBarcode;
        });

        // 将数组转换回逗号拼接的字符串
        rsCodeList = arr.join(',');

        // console.log('将数组转换回逗号拼接的字符串rsCodeList:'+rsCodeList)
        if (rsCodeList.length > 0) {
            // 刷新表格数据
            doSerchRsCodeList(rsCodeList);
        } else {
            // 清空表格数据
            $api.html($api.byId("tbodyHtml"), "");
            arrSave = [];
        }


    };


    function removeAll(list) {
        num = list.length;
        $("#num").val(num);
        setTable(list);
        arrSave = list;
    };



    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>